package org.mcflier.appuntamento.core.properties;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Properties;

import org.mcflier.appuntamento.core.exception.PropertiesException;

public class PropertiesManager {
	
	private static final String PROPERTIES_FILEPATH = "appuntamento.properties";

	private static PropertiesManager instance;
	
	static{
		instance = null;
	}
	
	public static PropertiesManager getInstance() throws PropertiesException{
		if(instance == null)
			instance = new PropertiesManager();
		
		return instance;
	}
	
	private Properties properties;
	
	private PropertiesManager() throws PropertiesException{
		this.properties = new Properties();
		InputStream input = this.getClass().getResourceAsStream(PROPERTIES_FILEPATH);
		try {
			this.properties.load(input);
			input.close();
		} catch (IOException e) {
			throw new PropertiesException("Error creating the app properties", e);
		}
	}
	
	public Properties getProperties(){
		return this.properties;
	}
	
	public void addProperty(String key, String value){
		if(key == null || value == null)
			throw new NullPointerException("Property key and value must not be null");
		
		this.properties.put(key, value);
	}
	
	public void storeProperties() throws PropertiesException{
		try {
			OutputStream out = new FileOutputStream(PROPERTIES_FILEPATH);
			this.properties.store(out, "Properties stored at "+Calendar.getInstance().getTime());
			out.close();
		} catch (IOException e) {
			throw new PropertiesException("Error storing the properties in its file", e);
		}
	}
}
